package parent

import (
	"anban/controllers"
	"anban/models"
	"anban/service"
	"github.com/astaxie/beego"
	"html/template"
	"strconv"
)

type UserController struct {
	controllers.BaseController
}

func (c *UserController) Index() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	p["convert"] = true
	c.Data["userInfo"] = service.GetUserInfo(p)

	c.Data["contact"] = beego.AppConfig.String("contact")
	c.Data["title"] = "用户中心"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/user-index.html"
}

func (c *UserController) FamilyMember() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	p = map[string]interface{}{}
	p["familySn"] = user.FamilySn
	p["status"] = 1
	p["relation"] = true
	c.Data["memberNum"], c.Data["memberList"] = service.GetUserList(p)

	c.Data["title"] = "家庭成员"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/user-family-member.html"
}

func (c *UserController) ParentAddressBook() {
	c.Data["title"] = "家长通讯录"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/parent-address-book.html"
}

func (c *UserController) ParentAddressBookLoadMore() {
	count, _ := beego.AppConfig.Int("loadcount")
	curPage, _ := strconv.Atoi(c.GetString("p"))
	if curPage <= 0 {
		curPage = 1
	}

	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	var classIds []int64
	p = map[string]interface{}{}
	p["familySn"] = user.FamilySn
	_, studentList := service.GetStudentList(p)
	for _, student := range studentList {
		classIds = append(classIds, student.Class.Id)
	}

	var studentIds []int64
	if len(classIds) > 0 {
		p = map[string]interface{}{}
		p["classIds"] = classIds
		_, classStudentList := service.GetStudentList(p)
		for _, classStudent := range classStudentList {
			studentIds = append(studentIds, classStudent.Id)
		}
	}

	var parentList []*models.User
	if len(studentIds) > 0 {
		p = map[string]interface{}{}
		p["studentIds"] = studentIds
		p["relation"] = true
		p["convert"] = true
		p["curPage"] = curPage
		p["perCount"] = count
		_, parentList = service.GetUserList(p)
	}

	c.Data["parentList"] = parentList
	c.TplName = "parent/parent-address-book-list.html"
}

func (c *UserController) SchoolAddressBook() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	p = map[string]interface{}{}
	p["withTeacher"] = true
	p["familySn"] = user.FamilySn
	_, c.Data["studentList"] = service.GetStudentList(p)

	c.Data["title"] = "校园通讯录"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/school-address-book.html"
}